package cn.school.demo.ui.search

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.school.demo.pojo.Article
import cn.school.demo.repository.SearchRepository

class SearchViewModel : ViewModel() {

    private val _searchHistory = MutableLiveData<MutableList<String>>()
    val searchHistory: LiveData<MutableList<String>>
        get() = _searchHistory

    private val _articleList = MutableLiveData<MutableList<Article>>()
    val articleList: LiveData<MutableList<Article>>
        get() = _articleList
    private val _isUpdate = MutableLiveData<Boolean>(false)
    val isUpdate: LiveData<Boolean> get() = _isUpdate

    private var _topSearchList: LiveData<MutableList<Article>>
    val topSearchList: LiveData<MutableList<Article>> get() = _topSearchList

    init {
        _searchHistory.value = mutableListOf()
        _topSearchList = SearchRepository().getTopSearchList()
        _articleList.value = mutableListOf(Article(articleName = "无相关文章信息"))
    }

    fun setSearchHistory(m: MutableList<String>?) {
        if (m.isNullOrEmpty()) {
            _searchHistory.value = mutableListOf()
        } else {
            _searchHistory.value = m!!
        }
    }

    fun getSearchedResult(searchContext: String) =
        SearchRepository().getSearchedResultList(searchContext)

    fun setArticleList(list: MutableList<Article>) {
        if (list.isNotEmpty()) {
            _articleList.value!!.clear()
            _articleList.value!!.addAll(list)
        } else {
            _articleList.value!!.clear()
            _articleList.value!!.addAll(mutableListOf(Article(articleName = "无相关文章信息")))
        }
        _isUpdate.value = !_isUpdate.value!!
    }
}